package junior.db.dao.mybatis.type;

import junior.db.dao.mybatis.interceptor.MybatisConfigurationHolder;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MybatisTypeHandler extends BaseTypeHandler<TypeValue> {
    
    @SuppressWarnings({"unchecked"})
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, TypeValue t, JdbcType jdbcType) throws SQLException {
        if (t == null || t.getValue() == null) {
            preparedStatement.setNull(i, jdbcType.TYPE_CODE);
        } else {
            Configuration configuration = MybatisConfigurationHolder.getConfiguration();
            if (configuration != null) {
                Class<Object> aliasType = configuration.getTypeAliasRegistry().resolveAlias(t.getType());
                TypeHandler<Object> handler = configuration.getTypeHandlerRegistry().getTypeHandler(aliasType);
                handler.setParameter(preparedStatement, i, t.getValue(), jdbcType);
            }
        }
    }
    
    @Override
    public TypeValue getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return null;
    }
    
    @Override
    public TypeValue getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return null;
    }
    
    @Override
    public TypeValue getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }
}
